﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using dnAnalytics.Math;
using dnAnalytics.Properties;

namespace dnAnalytics.Statistics.Distributions
{
    /// <summary>
    /// The Beta distribution is a distribution over the interval [0,1]. It is parameterized by
    /// two real number a,b >= 0.
    /// </summary>
    /// <remarks>The distribution will use the <see cref="System.Random"/> by default. 
    /// Users can set the random number generator by using the <see cref="RandomNumberGenerator"/> property.
    /// 
    /// The statistics classes will check all the incoming parameters whether they are in the allowed
    /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters
    /// to false, all parameter checks can be turned off.</remarks>
    public class Beta : IContinuousDistribution
    {
        // Beta parameter a.
        private readonly double mA;

        // Beta parameter b.
        private readonly double mB;

        /// <summary>
        /// Constructs a Beta distribution.
        /// </summary>
        /// <param name="a">The first parameter of the Beta distribution.</param>
        /// <param name="b">The second parameter of the Beta distribution.</param>
        /// <exception cref="ArgumentOutOfRangeException">If any of the Beta parameters are negative.</exception>
        public Beta(double a, double b)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(a, b);
            }
            
            mA = a;
            mB = b;
            RandomNumberGenerator = new System.Random();
        }

        /// <summary>
        /// The first parameter of the Beta distribution.
        /// </summary>
        /// <value></value>
        public double A
        {
            get { return mA; }
        }

        /// <summary>
        /// The second parameter of the Beta distribution.
        /// </summary>
        /// <value></value>
        public double B
        {
            get { return mB; }
        }

        /// <summary>
        /// A string representation of the distribution.
        /// </summary>
        public override string ToString()
        {
            return "Beta(A = " + mA + ", B = " + mB + ")";
        }

        #region IDistribution

        /// <summary>
        /// The mean of the distribution.
        /// </summary>
        /// <value></value>
        public double Mean
        {
            get { return mA/(mA + mB); }
        }

        /// <summary>
        /// The standard deviation of the distribution.
        /// </summary>
        /// <value></value>
        public double StdDev
        {
            get { return System.Math.Sqrt((mA*mB)/((mA + mB)*(mA + mB)*(mA + mB + 1.0))); }
        }

        /// <summary>
        /// The variance of the distribution.
        /// </summary>
        /// <value></value>
        public double Variance
        {
            get { return (mA*mB)/((mA + mB)*(mA + mB)*(mA + mB + 1.0)); }
        }

        /// <summary>
        /// The entropy of the distribution.
        /// </summary>
        /// <value></value>
        public double Entropy
        {
            get
            {
                return Math.SpecialFunctions.BetaLn(mA, mB)
                       - (mA - 1.0) * Math.SpecialFunctions.DiGamma(mA)
                       - (mB - 1.0) * Math.SpecialFunctions.DiGamma(mB)
                       + (mA + mB - 2.0) * Math.SpecialFunctions.DiGamma(mA + mB);
            }
        }

        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <value>The random number generator used to generate a random sample.</value>
        public System.Random RandomNumberGenerator { get; set; }

        #endregion

        #region IContinuousDistribution Members

        /// <summary>
        /// The mode of the distribution.
        /// </summary>
        /// <value></value>
        public double Mode
        {
            get { return (mA - 1) / (mA + mB - 2); }
        }

        /// <summary>
        /// The median of the distribution.
        /// </summary>
        /// <value></value>
        public double Median
        {
            get { throw new Exception("Not yet implemented"); }
        }

        /// <summary>
        /// Evaluates the probability density function for a the Beta distribution.
        /// </summary>
        public double Density(double x)
        {
            double b = SpecialFunctions.Gamma(mA + mB) / (SpecialFunctions.Gamma(mA) * SpecialFunctions.Gamma(mB));
            return b * System.Math.Pow(x, mA - 1.0) * System.Math.Pow(1.0 - x, mB - 1.0);
        }

        /// <summary>
        /// Samples a Beta distributed random variable.
        /// </summary>
        public double Sample()
        {
            return DoSample(RandomNumberGenerator, mA, mB);
        }

        /// <summary>
        /// Samples an array of Beta distributed random variables.
        /// </summary>
        /// <param name="n">The number of variables needed.</param>
        public double[] Sample(int n)
        {
            return DoSample(RandomNumberGenerator, n, mA, mB);
        }

        #endregion

        /// <summary>
        /// Samples a Beta distributed random variable.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="a">The first parameter of the Beta distribution.</param>
        /// <param name="b">The second parameter of the Beta distribution.</param>
        public static double Sample(System.Random rnd, double a, double b)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(a, b);
            }
            
            return DoSample(rnd, a, b);
        }

        /// <summary>
        /// Samples an array of Beta distributed random variables.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="a">The first parameter of the Beta distribution.</param>
        /// <param name="b">The second parameter of the Beta distribution.</param>
        public static double[] Sample(System.Random rnd, int n, double a, double b)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(a, b);
            }
            
            return DoSample(rnd, n, a, b);
        }


        private static double DoSample(System.Random rnd, double a, double b)
        {
            double x = Gamma.Sample(rnd, a, 1.0);
            double y = Gamma.Sample(rnd, b, 1.0);
            return x/(x + y);
        }

        private static double[] DoSample(System.Random rnd, int n, double a, double b)
        {
            double[] arr = new double[n];
            for (int i = 0; i < n; i++)
            {
                arr[i] = DoSample(rnd, a, b);
            }
            return arr;
        }

        private static void CheckParameters(double a, double b)
        {
            if (a < 0.0)
            {
                throw new ArgumentOutOfRangeException("a", Resources.ParameterCannotBeNegative);
            }
            if (b < 0.0)
            {
                throw new ArgumentOutOfRangeException("b", Resources.ParameterCannotBeNegative);
            }
        }
    }
}